package com.java.simple.smallspring.context.support;

import com.java.simple.smallspring.beans.factory.FactoryBean;
import com.java.simple.smallspring.beans.factory.InitializingBean;
import com.java.simple.smallspring.core.convert.ConversionService;
import com.java.simple.smallspring.core.convert.converter.Converter;
import com.java.simple.smallspring.core.convert.converter.ConverterFactory;
import com.java.simple.smallspring.core.convert.converter.ConverterRegistry;
import com.java.simple.smallspring.core.convert.converter.GenericConverter;
import com.java.simple.smallspring.core.convert.support.DefaultConversionService;
import com.java.simple.smallspring.core.convert.support.GenericConversionService;
import com.sun.istack.internal.Nullable;
import lombok.Setter;

import java.util.Objects;
import java.util.Set;

/**
 * @author zhoujunlin
 * @date 2022年11月19日 14:32
 * @desc 提供创建ConversionService工厂
 */
public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {

    @Nullable
    @Setter
    private Set<?> converts;

    @Nullable
    private GenericConversionService conversionService;

    @Override
    public ConversionService getObject() throws Exception {
        return conversionService;
    }

    @Override
    public Class<?> getObjectType() {
        return conversionService.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.conversionService = new DefaultConversionService();
        registerConverters(converts, conversionService);
    }

    private void registerConverters(Set<?> converts, ConverterRegistry converterRegistry) {
        if (Objects.nonNull(converts)) {
            for (Object convert : converts) {
                if (convert instanceof GenericConverter) {
                    converterRegistry.addConverter((GenericConverter) convert);
                } else if (convert instanceof Converter<?, ?>) {
                    converterRegistry.addConverter((Converter<?, ?>) convert);
                } else if (convert instanceof ConverterFactory<?, ?>) {
                    converterRegistry.addConverterFactory((ConverterFactory<?, ?>) convert);
                } else {
                    throw new IllegalArgumentException("Each converter object must implement one of the" +
                            "Converter, ConverterFactory, or GenericConverter interfaces");
                }
            }
        }
    }

}
